package com.demo.quartz.controller;

import com.demo.quartz.config.helloJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author daifeng
 * @create 2021-11-01-15:44
 */
@RestController
public class JobController {

//    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
//    @Autowired
//    private SchedulerFactoryBean schedulerFactoryBean;

    // 调度器
    @Autowired
    private Scheduler scheduler;

    @Scheduled(cron = "0/3 * * * * ? ")
    public void text(){
        //每3秒执行一次
        System.out.println("定时任务执行啦："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    /**
     * 以请求的方式去开启定时任务
     * 该任务的执行周期为 ： 请求执行的时间起 每秒执行一次 且一直执行
     * @throws SchedulerException
     */
    @PostMapping(value = "testTask1")
    public void testTask1( )throws SchedulerException {

        //可用于传值给job   具体看helloJob类如何取值使用
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("jobDetail1","jobDetail1");
        JobDataMap jobDataMap2 = new JobDataMap();
        jobDataMap2.put("trigger1","这是jobDetail1的trigger");

        // 1、创建JobDetail实例，并与PrintWordsJob类绑定(Job执行内容)
        JobDetail jobDetail = JobBuilder.newJob(helloJob.class).usingJobData(jobDataMap)
                .withIdentity("job1", "group1").build();

        // 2、构建Trigger(触发器)实例,每隔1s执行一次
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1")
                .usingJobData(jobDataMap2) //存值到jobDataMap Job类中能取出
                // 可设置触发时间
                .startNow()//立即生效
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInSeconds(1)//每隔1s执行一次
                 .repeatForever()).build();//一直执行
        //3、执行
        scheduler.scheduleJob(jobDetail, trigger);
        scheduler.start();
    }

    /**
     * 以请求的方式去开启定时任务
     * 该任务的执行周期为 ： 请求执行的时间起 每天早上8点都会执行一次  持续一周即endAt的时间
     * @throws SchedulerException
     */
    @PostMapping(value = "testTask2")
    public void testTask2( )throws SchedulerException {

        // 获取一周后的日期
        Date endDate = new Date();
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DATE, +7);
        Date d = now.getTime();

        //可用于传值给job
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("jobDetail1","jobDetail1");
        JobDataMap jobDataMap2 = new JobDataMap();
        jobDataMap2.put("trigger1","这是jobDetail1的trigger");

        // 1、创建JobDetail实例，并与PrintWordsJob类绑定(Job执行内容)
        JobDetail jobDetail = JobBuilder.newJob(helloJob.class).usingJobData(jobDataMap)
                .withIdentity("job1", "group1").build();
        // 2、构建Trigger实例,每隔1s执行一次
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1")
                .usingJobData(jobDataMap2) //存值到jobDataMap
                /**
                 * 实现了程序运行5s后开始执行Job，执行Job 5s后结束执行：可以用来设置定时任务的有效时间
                 */
                .startNow() // 立即触发
                .endAt(d) // 表示该任务在一周后自动停止   ps:表示触发器结束触发的时间;
                //使用cron表达式    每天中午8点触发
                .withSchedule(CronScheduleBuilder.cronSchedule("0 0 8 * * ?"))
                .build();

        //3、执行
        scheduler.scheduleJob(jobDetail, trigger);
        scheduler.start();
    }

    /**
     * 以请求的方式去开启定时任务
     * 该任务的执行周期为 ： 请求执行的时间的第二天开始 每天早上8点都会执行一次  持续一周即endAt的时间
     * @throws SchedulerException
     */
    @PostMapping(value = "testTask3")
    public void testTask3( )throws SchedulerException {


        Calendar now = Calendar.getInstance();
        now.setTime(new Date());
        // 获取一周后的日期
        now.add(Calendar.DATE, +7);
        Date endAt = now.getTime();

        // 获取一天后的日期
        now.add(Calendar.DATE, +1);
        Date startAt = now.getTime();

        //可用于传值给job
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("jobDetail1","jobDetail1");
        JobDataMap jobDataMap2 = new JobDataMap();
        jobDataMap2.put("trigger1","这是jobDetail1的trigger");

        // 1、创建JobDetail实例，并与PrintWordsJob类绑定(Job执行内容)
        JobDetail jobDetail = JobBuilder.newJob(helloJob.class).usingJobData(jobDataMap)
                .withIdentity("job1", "group1").build();
        // 2、构建Trigger实例,每隔1s执行一次
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1")
                .usingJobData(jobDataMap2) //存值到jobDataMap
                /**
                 * 实现了程序运行5s后开始执行Job，执行Job 5s后结束执行：可以用来设置定时任务的有效时间
                 */
                .startAt(startAt) // 立即触发
                .endAt(endAt) // 表示该任务在一周后自动停止   ps:表示触发器结束触发的时间;
                //使用cron表达式    每天中午8点触发
                .withSchedule(CronScheduleBuilder.cronSchedule("0 0 8 * * ?"))
                .build();

        //3、执行
        scheduler.scheduleJob(jobDetail, trigger);
        scheduler.start();
    }

    /**
     * 移除定时任务
     * @param jobName  JobDetail的name
     * @param jobGroup JobDetail的分组名
     * @throws SchedulerException
     */
    @RequestMapping("/deleteJob")
    public void deleteJob(String jobName,String jobGroup) throws SchedulerException
    {
//        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey=new JobKey(jobName,jobGroup);
        scheduler.deleteJob(jobKey);
    }
    /**
     * 暂停定时任务
     * @param jobName
     * @param jobGroup
     * @throws SchedulerException
     */
    @RequestMapping("/pauseJob")
    public void pauseJob(String jobName,String jobGroup) throws SchedulerException
    {
//        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey=new JobKey(jobName,jobGroup);
        // scheduler.shutdown();
        scheduler.pauseJob(jobKey);
    }
    /**
     * 恢复定时任务
     * @param jobName
     * @param jobGroup
     * @throws SchedulerException
     */
    @RequestMapping("/resumeJob")
    public void resumeJob(String jobName,String jobGroup) throws SchedulerException
    {
//        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey triggerKey=new JobKey(jobName,jobGroup);
        scheduler.resumeJob(triggerKey);
    }
    /**
     * 清空所有当前scheduler对象下的定时任务【目前只有全局一个scheduler对象】
     * @throws SchedulerException
     */
    @RequestMapping("/clearAll")
    public void clearAll() throws SchedulerException {
//        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        scheduler.clear();
    }


    // 以请求的方式去开启定时任务
    @PostMapping(value = "testTasks")
    public void testTasks( )throws SchedulerException {

        Date startDate = new Date();
        startDate.setTime(startDate.getTime() + 5000);

        Date endDate = new Date();
        endDate.setTime(startDate.getTime() + 5000);

        // 1、创建调度器Scheduler
        //可用于传值给job
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("jobDetail1","jobDetail1");
        JobDataMap jobDataMap2 = new JobDataMap();
        jobDataMap2.put("trigger1","这是jobDetail1的trigger");

        // 2、创建JobDetail实例，并与PrintWordsJob类绑定(Job执行内容)
        JobDetail jobDetail = JobBuilder.newJob(helloJob.class).usingJobData(jobDataMap)
                .withIdentity("job1", "group1").build();
        // 3、构建Trigger实例,每隔1s执行一次
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1")
                .usingJobData(jobDataMap2) //存值到jobDataMap
                // 可设置触发时间
                //new Trigger().startAt():表示触发器首次被触发的时间;
                //new Trigger().endAt():表示触发器结束触发的时间;
                .startNow()//立即生效
                /**
                 * 实现了程序运行5s后开始执行Job，执行Job 5s后结束执行：
                 */
//                .startAt(startDate)
//                .endAt(endDate)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        // 可以使用cron表达式
                        // .withSchedule(CronScheduleBuilder.cronSchedule("* 30 10 ? * 1/5 2018"))
                        .withIntervalInSeconds(1)//每隔1s执行一次
                        .repeatForever()).build();//一直执行

        //4、执行
        scheduler.scheduleJob(jobDetail, trigger);
        System.out.println("--------scheduler start ! ------------");
        scheduler.start();

//        //睡眠
//        try {
//            TimeUnit.MINUTES.sleep(1);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        scheduler.shutdown();
//        System.out.println("--------scheduler shutdown ! ------------");

    }

}
